package pri.service.order;

import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import pri.common.Common;
import pri.dao.OderDetailMapper;
import pri.dao.OrderListMapper;
import pri.dao.ProductMapper;
import pri.dao.RecAddressMapper;
import pri.pojo.*;
import pri.service.user.UserService;

import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class OrderServiceImpl implements OrderService {
    @Autowired
    OderDetailMapper oderDetailMapper;
    @Autowired
    OrderListMapper orderListMapper;
    @Autowired
    ProductMapper productMapper;
    @Autowired
    UserService userService;
    @Autowired
    RecAddressMapper recAddressMapper;


    @Override
    public List<SaleData> getSale(Date startTime, Date endTime){
        //先通过时间筛选订单
        OrderListExample orderListExample = new OrderListExample();
        orderListExample.createCriteria().andCreatetime1Between(startTime,endTime);
        List<OrderList> orderLists = orderListMapper.selectByExample(orderListExample);
        System.out.println(orderLists);


        Map<Integer,Integer> map = new HashMap<>();
        //通过订单号循环遍历
        for (OrderList ol:orderLists) {
            OderDetailExample oderDetailExample = new OderDetailExample();
            oderDetailExample.createCriteria().andOrderIdEqualTo(ol.getOrderId());
            List<OderDetail> oderDetails = oderDetailMapper.selectByExample(oderDetailExample);
            //通过产品号循环遍历
            for (OderDetail od:oderDetails){
                ProductExample productExample = new ProductExample();
                productExample.createCriteria().andProductIdEqualTo(Integer.valueOf(od.getProductId()));
                List<Product> products = productMapper.selectByExample(productExample);
                //得到商品信息
                if (products == null || products.isEmpty()){
                    continue;
                }
                int category = products.get(0).getCategoryId();
                if (map.containsKey(category)){
                    map.put(category,map.get(category)+od.getProductCount());
                }else {
                    map.put(category,1);
                }
            }
        }

        System.out.println("hello:"+map);
        //循环完以后返回pojo
        List<SaleData> saleDatas = new ArrayList<>();
        for(int key : map.keySet()){
            SaleData saleDatass = new SaleData();
            saleDatass.setCategory_id(String.valueOf(key));
            saleDatass.setCount(String.valueOf(map.get(key)));
            saleDatas.add(saleDatass);
        }

        return saleDatas;
    }

    @Override
    public int getOrderNum(Date startTime, Date endTime){
        //先通过时间筛选订单
        OrderListExample orderListExample = new OrderListExample();
        orderListExample.createCriteria().andCreatetime1Between(startTime,endTime);
        List<OrderList> orderLists = orderListMapper.selectByExample(orderListExample);
        return orderLists.size();
    }


    @Override
    public List<Map> getStatusOrder(String page, String limit, String status) {
        OrderListExample orderListExample = new OrderListExample();

        String lastTime = "createtime1";

        if (status.equals("recent")){
            String tomorrow = DateUtil.tomorrow().toString();
            Date date = DateUtil.parse(tomorrow);
            Date historyDate = DateUtil.offset(date, DateField.MONTH, -3);
            orderListExample.createCriteria().andCreatetime1Between(historyDate,date);
            lastTime ="createtime1";
        }


        if (status.equals("waitpay")){
            orderListExample.createCriteria().andStatusEqualTo(Common.ORDER_STATUS_1);
            lastTime ="createtime1";
        }

        if (status.equals("waitsend")){
            orderListExample.createCriteria().andStatusEqualTo(Common.ORDER_STATUS_2);
            lastTime ="createtime2";
        }

        if (status.equals("waitconfirm")){
            orderListExample.createCriteria().andStatusEqualTo(Common.ORDER_STATUS_3);
            lastTime ="createtime3";
        }

        if (status.equals("waitcomment")){
            orderListExample.createCriteria().andStatusEqualTo(Common.ORDER_STATUS_4);
            lastTime ="createtime4";
        }

        if (status.equals("success")){
            orderListExample.createCriteria().andStatusEqualTo(Common.ORDER_STATUS_5);
            lastTime ="createtime5";
        }

        String num = String.valueOf((Integer.valueOf(page)-1)*Integer.valueOf(limit));
        orderListExample.setOrderByClause(lastTime+" desc limit "+num+" , "+ limit);
        List<OrderList> orderLists = orderListMapper.selectByExample(orderListExample);
        List<Map> maps = new ArrayList<>();
        for (OrderList ol:orderLists){
            Map<String,Object> map = new HashMap<>();
            map.put("oid",ol.getOrderId());
            //通过oid获取对应所有的产品信息
            OderDetailExample oderDetailExample = new OderDetailExample();
            oderDetailExample.createCriteria().andOrderIdEqualTo(ol.getOrderId());
            List<OderDetail> orderDetails = oderDetailMapper.selectByExample(oderDetailExample);
            List<Map> detailmaps = new ArrayList<>();
            for (OderDetail od:orderDetails){
                Map<String,String> detailmap = new HashMap<>();
                detailmap.put("product_name",od.getProductName());
                detailmap.put("product_price",String.valueOf(od.getProductOriPrice()));
                detailmap.put("product_count",String.valueOf(od.getProductCount()));
                detailmaps.add(detailmap);
            }
            map.put("product",detailmaps);
            //通过userId获取用户网名
            String customer = userService.getUserById(ol.getUserId()).getNickName();
            map.put("customer",customer);
            map.put("status",ol.getStatus());
            map.put("real_price",ol.getTotal());
            //时间轮询 节约代码 找到最近状态的时间
            String time = "";
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy.MM.dd HH:mm:ss");
            if (ol.getCreatetime1() != null){
                time = sdf.format(ol.getCreatetime1());
            }
            if (ol.getCreatetime2() != null){
                time = sdf.format(ol.getCreatetime2());
            }
            if (ol.getCreatetime3() != null){
                time = sdf.format(ol.getCreatetime3());
            }
            if (ol.getCreatetime4() != null){
                time = sdf.format(ol.getCreatetime4());
            }
            if (ol.getCreatetime5() != null){
                time = sdf.format(ol.getCreatetime5());
            }
            if (ol.getCreatetime6() != null){
                time = sdf.format(ol.getCreatetime6());
            }
            map.put("time",time);
            maps.add(map);
        }
        return maps;
    }


    @Override
    public RecAddress getAddressByOrderId(String oid){
        OderDetailExample oderDetailExample = new OderDetailExample();
        oderDetailExample.createCriteria().andOrderIdEqualTo(oid);
        List<OderDetail> oderDetails = oderDetailMapper.selectByExample(oderDetailExample);
        String rec_id = oderDetails.get(0).getRecAddress();
        RecAddress recAddresse = recAddressMapper.selectByPrimaryKey(Integer.valueOf(rec_id));
        return recAddresse;
    }

    @Override
    public boolean sendProduct(String oid, String expressCom, String expressNum){
        try {
            OderDetail oderDetail = new OderDetail();
            oderDetail.setExpressNum(expressNum);
            oderDetail.setExpressComId(expressCom);
            OderDetailExample oderDetailExample = new OderDetailExample();
            oderDetailExample.createCriteria().andOrderIdEqualTo(oid);
            oderDetailMapper.updateByExampleSelective(oderDetail,oderDetailExample);
            changeOrderStatus(oid,Common.ORDER_STATUS_3);
            return true;
        }catch (Exception e){
            e.printStackTrace();
            return false;
        }
    }

    @Override
    public void changeOrderStatus(String oid, String status) {
        System.out.println(oid);
        //改list表
        OrderListExample ole = new OrderListExample();
        ole.createCriteria().andOrderIdEqualTo(oid);
        OrderList ol = new OrderList();
        ol.setStatus(status);
        Date now = new Date();
        //修改状态需要更新时间
        switch (status){
            case Common.ORDER_STATUS_2:
                ol.setCreatetime2(now);
                break;
            case Common.ORDER_STATUS_3:
                ol.setCreatetime3(now);
                break;
            case Common.ORDER_STATUS_4:
                ol.setCreatetime4(now);
                break;
            case Common.ORDER_STATUS_5:
                ol.setCreatetime5(now);
                break;
        }
        orderListMapper.updateByExampleSelective(ol,ole);

        //改detail表
        OderDetailExample ode = new OderDetailExample();
        ode.createCriteria().andOrderIdEqualTo(oid);
        OderDetail od = new OderDetail();
        od.setOrderStatus(status);
        oderDetailMapper.updateByExampleSelective(od,ode);
    }

}
